package com.mySampleApplication.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;



/**
 * Created by Navuhodonosor on 12/16/2014.
 */

public class MySampleApplication implements EntryPoint {
    private TextBox name = new TextBox();
    private TextBox lastname = new TextBox();
    private TextBox login = new TextBox();
    private TextBox password = new TextBox();
    private Button createUser = new Button("Creat");
    private VerticalPanel panel = new VerticalPanel();
    private VerticalPanel labelPanel = new VerticalPanel();
    public HorizontalPanel horizontalPanel = new HorizontalPanel();

    private Label nameLabel = new Label("Name");
    private Label lastnameLabel = new Label("Last name");
    private Label loginLabel = new Label("Login");
    private Label passwordLabel = new Label("Password");

    private MySampleApplicationServiceAsync service = MySampleApplicationService.App.getInstance();


    public void onModuleLoad() {
        panel.add(name);
        panel.add(lastname);
        panel.add(login);
        panel.add(password);
        panel.add(createUser);
        labelPanel.add(nameLabel);
        labelPanel.add(lastnameLabel);
        labelPanel.add(loginLabel);
        labelPanel.add(passwordLabel);
        horizontalPanel.add(panel);
        horizontalPanel.add(labelPanel);
        RootPanel.get("stocklist").add(horizontalPanel);

        createUser.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                if (!name.getText().isEmpty() && !lastname.getText().isEmpty() && !login.getText().isEmpty() && !password.getText().isEmpty()){
                    service.addUser(name.getText(), lastname.getText(), login.getText(), password.getText(), new AsyncCallback<User>() {
                        @Override
                        public void onFailure(Throwable caught) {
                            Window.alert("RPC failed to create new user");
                            System.out.println(caught.getMessage());
                        }

                        @Override
                        public void onSuccess(User result) {
                            if (result.isFlag()){
                                Window.alert("User already exists");
                            } else {
                                Window.alert("Data was sent");
                                System.out.println(result);
                            }
                        }
                    });
                } else Window.alert("Missing field");
            }
        });

    }



}
